<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryFormRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="门店" prop="shopId">
        <el-select v-model="queryParams.shopId" placeholder="请选择" clearable filterable style="width: 180px">
          <el-option v-for="s in shopOptions" :key="s.value" :label="s.label" :value="s.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="项目" prop="itemId">
        <el-select v-model="queryParams.itemId" placeholder="请选择" clearable filterable style="width: 180px">
          <el-option v-for="p in projectOptions" :key="p.value" :label="p.label" :value="p.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="申请用户" prop="applyUser">
        <el-input v-model="queryParams.applyUser" placeholder="请输入申请用户" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="申请时间" prop="applyTimeRange" style="width: 360px">
        <el-date-picker v-model="applyTimeRange" type="daterange" value-format="YYYY-MM-DD" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期" />
      </el-form-item>
      <el-form-item label="预约状态" prop="orderStatus">
        <el-select v-model="queryParams.orderStatus" placeholder="请选择预约状态" clearable style="width: 180px">
          <el-option v-for="o in statusOptions" :key="o.value" :label="o.label" :value="o.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" :icon="Search" @click="handleQuery">搜索</el-button>
        <el-button :icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          :icon="Plus"
          @click="handleAdd"
          v-hasPermi="['system:orderinfo:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          :icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:orderinfo:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          :icon="Download"
          :loading="exportLoading"
          @click="handleExport"
          v-hasPermi="['system:orderinfo:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="orderinfoList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" width="70" type="index" :index="indexMethod" />
      <el-table-column label="申请用户" align="center">
        <template #default="scope">
          {{ labelOf(userOptions, scope.row.applyUserId || scope.row.apply_user_id || scope.row.userId) || scope.row.userName }}
        </template>
      </el-table-column>
      <el-table-column label="门店" align="center">
        <template #default="scope">{{ scope.row.shopName }}</template>
      </el-table-column>
      <el-table-column label="项目" align="center">
        <template #default="scope">{{ scope.row.itemName }}</template>
      </el-table-column>
      <el-table-column label="预约顾问" align="center">
        <template #default="scope">{{ scope.row.applyConsultantName || scope.row.applyUserName || scope.row.applyConsultant }}</template>
      </el-table-column>
      <el-table-column label="预约时间" align="center" prop="applyTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.applyTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="预约状态" align="center" prop="status">
        <template #default="scope">
          {{ formatStatus(scope.row.status) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button
            type="text"
            :icon="Edit"
            @click="handleUpdate(scope.row)"
            v-if="isEditable(scope.row)"
            v-hasPermi="['system:orderinfo:edit']"
          >修改</el-button>
          <el-button
            type="text"
            :icon="Edit"
            v-if="isAppointed(scope.row)"
            @click="handleConfirmReceive(scope.row)"
            v-hasPermi="['system:orderinfo:edit']"
          >确认接待</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      v-model:total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改项目订单对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="门店ID" prop="shopId">
          <template v-if="onlyConsultantEditable">
            <span>{{ labelOf(shopOptions, form.shopId) || '-' }}</span>
          </template>
          <template v-else>
            <el-select v-model="form.shopId" placeholder="请选择" clearable filterable style="width: 100%">
              <el-option v-for="s in shopOptions" :key="s.value" :label="s.label" :value="s.value" />
            </el-select>
          </template>
        </el-form-item>
        <el-form-item label="项目" prop="itemId">
          <template v-if="onlyConsultantEditable">
            <span>{{ labelOf(projectOptions, form.itemId) || '-' }}</span>
          </template>
          <template v-else>
            <el-select v-model="form.itemId" placeholder="请选择" clearable filterable style="width: 100%">
              <el-option v-for="p in projectOptions" :key="p.value" :label="p.label" :value="p.value" />
            </el-select>
          </template>
        </el-form-item>
        <el-form-item label="申请用户" prop="applyUserId">
          <template v-if="onlyConsultantEditable">
            <span>{{ labelOf(userOptions, form.applyUserId) || '-' }}</span>
          </template>
          <template v-else>
            <el-select v-model="form.applyUserId" placeholder="请选择申请用户" clearable filterable style="width: 100%">
              <el-option v-for="u in userOptions" :key="u.value" :label="u.label" :value="u.value" />
            </el-select>
          </template>
        </el-form-item>
        <el-form-item label="申请时间" prop="applyTime">
          <template v-if="onlyConsultantEditable">
            <span>{{ form.applyTime || '-' }}</span>
          </template>
          <template v-else>
            <el-date-picker v-model="form.applyTime" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择申请时间" style="width: 100%" />
          </template>
        </el-form-item>
        <el-form-item label="预约顾问" prop="applyConsultant">
          <div v-if="onlyConsultantEditable" style="margin-bottom: 6px; color: var(--el-text-color-secondary);">
            当前：{{ labelOf(consultantOptions, form.applyConsultant) || '-' }}
          </div>
          <el-select v-model="form.applyConsultant" :placeholder="onlyConsultantEditable ? '请选择新的预约顾问' : '请选择预约顾问'" clearable filterable style="width: 100%">
            <el-option v-for="c in consultantOptions" :key="c.value" :label="c.label" :value="c.value" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Orderinfo">
import { ref, reactive, toRefs } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, Plus, Edit, Download } from '@element-plus/icons-vue'
import { listOrderinfo, getOrderinfo, addOrderinfo, updateOrderinfo, exportOrderinfo } from "@/api/system/orderinfo";
import { parseTime } from '@/utils/ruoyi'
import request, { download } from '@/utils/request'
import { listShopItem as listProjects } from '@/api/system/shopItem'
import { listShopItem as listShops } from '@/api/system/shopIndex'
import { listConsultants } from '@/api/system/consultant'
import { listUser } from '@/api/system/user'

const queryFormRef = ref()
const formRef = ref()
const state = reactive({
  // 遮罩层
  loading: true,
  // 导出遮罩层
  exportLoading: false,
  // 选中数组
  ids: [],
  // 非单个禁用
  single: true,
  // 非多个禁用
  multiple: true,
  // 显示搜索条件
  showSearch: true,
  // 总条数
  total: 0,
  // 项目订单表格数据
  orderinfoList: [],
  // 弹出层标题
  title: "",
  // 是否显示弹出层
  open: false,
  // 查询参数
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    shopId: undefined,
    itemId: undefined,
    applyUser: undefined,
    orderStatus: undefined,
    applyBeginTime: undefined,
    applyEndTime: undefined,
  },
  // 表单参数
  form: {},
  // 表单校验
  rules: {
    shopId: [{ required: true, message: '请选择门店', trigger: 'change' }],
    itemId: [{ required: true, message: '请选择项目', trigger: 'change' }],
    applyUserId: [{ required: true, message: '请选择申请用户', trigger: 'change' }],
    applyTime: [{ required: true, message: '请选择申请时间', trigger: 'change' }],
    applyConsultant: [{ required: true, message: '请选择预约顾问', trigger: 'change' }]
  }
})

const { loading, exportLoading, showSearch, total, orderinfoList, title, open, queryParams, form, rules, single, multiple } = toRefs(state)
const onlyConsultantEditable = ref(false)

const shopOptions = ref([])
const projectOptions = ref([])
const statusOptions = ref([])
const userOptions = ref([])
const consultantOptions = ref([])

/** 查询项目订单列表 */
function getList() {
  loading.value = true
  listOrderinfo(queryParams.value).then(response => {
    orderinfoList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

/** 表格序号（全局序号） */
function indexMethod(index) {
  const p = queryParams.value || {}
  const pageNum = Number(p.pageNum || 1)
  const pageSize = Number(p.pageSize || 10)
  return (pageNum - 1) * pageSize + index + 1
}

/** 选择首个可用字段展示 */
function pick(row, keys) {
  for (const k of keys) {
    const v = row && row[k]
    if (v !== undefined && v !== null && v !== '') return v
  }
  return ''
}

/** 取消按钮 */
function cancel() {
  open.value = false
  reset()
}

/** 表单重置 */
function reset() {
  form.value = {
    id: null,
    shopId: null,
    userId: null,
    applyUserId: null,
    userName: null,
    userPhone: null,
    orderCode: null,
    orderTime: null,
    outTradeNo: null,
    orderType: null,
    accountAmount: null,
    sumAmount: null,
    payType: null,
    payment1: null,
    payment2: null,
    payment3: null,
    payment4: null,
    payment5: null,
    payment6: null,
    payment7: null,
    payment8: null,
    payment9: null,
    cardAmount: null,
    payTime: null,
    status: getStatusCodeByLabel('已预约') || '1',
    remark: null,
    orderFile: null,
    createTime: null,
    createBy: null,
    updateTime: null,
    updateBy: null
  }
  formRef.value?.resetFields()
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  // 映射时间范围
  if (Array.isArray(applyTimeRange.value) && applyTimeRange.value.length === 2) {
    queryParams.value.applyBeginTime = applyTimeRange.value[0]
    queryParams.value.applyEndTime = applyTimeRange.value[1]
  } else {
    queryParams.value.applyBeginTime = undefined
    queryParams.value.applyEndTime = undefined
  }
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  queryFormRef.value?.resetFields()
  applyTimeRange.value = []
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  state.ids = selection.map(item => item.id)
  state.single = selection.length!==1
  state.multiple = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  loadDialogOptions().then(() => {
    open.value = true
    title.value = "添加门店项目预约"
    onlyConsultantEditable.value = false
  })
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const id = row.id || state.ids[0]
  Promise.all([
    getOrderinfo(id),
    loadDialogOptions()
  ]).then(([response]) => {
    form.value = response.data
    // 兼容可能的字段命名
    form.value.shopId = form.value.shopId || form.value.shop_id || form.value.shop
    form.value.itemId = form.value.itemId || form.value.item_id || form.value.item
    form.value.applyUserId = form.value.applyUserId || form.value.apply_user_id || form.value.applyId || form.value.apply_id || form.value.userId
    form.value.applyTime = form.value.applyTime || form.value.apply_time
    form.value.applyConsultant = form.value.applyConsultant || form.value.apply_consultant || form.value.applyUserId
    open.value = true
    title.value = "修改门店项目预约"
    onlyConsultantEditable.value = true
  })
}

/** 提交按钮 */
function submitForm() {
  formRef.value?.validate(valid => {
    if (valid) {
      const formData = { ...form.value }
      if (form.value.id != null) {
        updateOrderinfo(formData).then(response => {
          ElMessage.success("修改成功")
          open.value = false
          getList()
        })
      } else {
        addOrderinfo(formData).then(response => {
          ElMessage.success("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

// 删除功能已下线，相关按钮与逻辑已移除

/** 导出按钮操作 */
function handleExport() {
  const queryParams = { ...state.queryParams }
  ElMessageBox.confirm('是否确认导出所有项目订单数据项?', "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    state.exportLoading = true
    return exportOrderinfo(queryParams)
  }).then(response => {
    download(response.msg)
    state.exportLoading = false
  }).catch(() => {})
}

// 预加载查询选项并拉取列表
function loadFilters() {
  return Promise.all([
    listShops({ pageNum: 1, pageSize: 999 }).then(res => {
      const rows = res?.rows || []
      shopOptions.value = rows.map(r => ({ label: r.shopName, value: r.id }))
    }),
    listProjects({ pageNum: 1, pageSize: 999 }).then(res => {
      const rows = res?.rows || []
      projectOptions.value = rows.map(r => ({ label: r.itemName, value: r.id }))
    }),
    Promise.all([
      listUser({ pageNum: 1, pageSize: 999 }),
      listConsultants({ pageNum: 1, pageSize: 999 })
    ]).then(([uRes, cRes]) => {
      const users = (uRes?.rows || []).map(u => ({ label: u.nickName || u.userName || u.phonenumber, value: u.userId }))
      const consultantIds = new Set((cRes?.rows || []).map(c => c.userId))
      userOptions.value = users.filter(u => !consultantIds.has(u.value))
    }),
    request({ url: '/system/dict/data/type/sys_item_apply_status', method: 'get' }).then(res => {
      const arr = res?.data || []
      statusOptions.value = arr.map(d => ({ label: d.dictLabel, value: String(d.dictValue) }))
    })
  ])
}

const applyTimeRange = ref([])

loadFilters().then(() => getList())

function loadDialogOptions() {
  return Promise.all([
    shopOptions.value.length ? Promise.resolve() : listShops({ pageNum: 1, pageSize: 999 }).then(res => {
      const rows = res?.rows || []
      shopOptions.value = rows.map(r => ({ label: r.shopName, value: r.id }))
    }),
    projectOptions.value.length ? Promise.resolve() : listProjects({ pageNum: 1, pageSize: 999 }).then(res => {
      const rows = res?.rows || []
      projectOptions.value = rows.map(r => ({ label: r.itemName, value: r.id }))
    }),
    Promise.all([
      listUser({ pageNum: 1, pageSize: 999 }),
      listConsultants({ pageNum: 1, pageSize: 999 })
    ]).then(([uRes, cRes]) => {
      const users = (uRes?.rows || []).map(u => ({ label: u.nickName || u.userName || u.phonenumber, value: u.userId }))
      const consultants = (cRes?.rows || []).map(c => ({ label: c.nickName || c.userName, value: c.userId }))
      const consultantIds = new Set(consultants.map(c => c.value))
      userOptions.value = users.filter(u => !consultantIds.has(u.value))
      consultantOptions.value = consultants
    })
  ])
}

function formatStatus(v) {
  const it = statusOptions.value.find(d => d.value === String(v))
  return it ? it.label : v
}

function labelOf(options, value) {
  const arr = Array.isArray(options) ? options : (options?.value ?? [])
  const it = (arr || []).find(o => String(o.value) === String(value))
  return it ? it.label : ''
}

function getStatusCodeByLabel(targetLabel) {
  const it = statusOptions.value.find(d => d.label === targetLabel) || statusOptions.value.find(d => (d.label || '').includes(targetLabel))
  return it ? String(it.value) : undefined
}

function isAppointed(row) {
  const code = row && row.status != null ? String(row.status) : ''
  const appointedCode = getStatusCodeByLabel('已预约')
  if (appointedCode && code === appointedCode) return true
  const label = formatStatus(row?.status)
  return label === '已预约'
}

function isEditable(row) {
  const code = row && row.status != null ? String(row.status) : ''
  const pendingCode = getStatusCodeByLabel('未接待') || '0'
  const appointedCode = getStatusCodeByLabel('已预约')
  if (code === pendingCode) return true
  if (appointedCode && code === appointedCode) return true
  const label = formatStatus(row?.status)
  return label === '未接待' || label === '已预约'
}

function handleConfirmReceive(row) {
  const id = row.id
  const receivedCode = getStatusCodeByLabel('已接待') || getStatusCodeByLabel('接待') || '2'
  const payload = { id, status: receivedCode }
  updateOrderinfo(payload).then(() => {
    ElMessage.success('已确认接待')
    getList()
  })
}
</script>